import java.util.HashMap;
import java.util.Map;

/**
 * 享元模式：把不需要的修改的数据存储起来，减少内存的消耗。
 * 比如：共享单车，实例化的单车是可以共享的，不需要再次实例化
 */
public class FlyweightPattern {
    public static void main(String[] args) {
        BicycleSharing bicycleSharing1 = BicycleSharingFactory.getBicycleSharing(1);
        BicycleSharing bicycleSharing2 = BicycleSharingFactory.getBicycleSharing(2);
        BicycleSharing bicycleSharing3 = BicycleSharingFactory.getBicycleSharing(3);
        bicycleSharing1.ride();
        bicycleSharing2.ride();
        bicycleSharing3.ride();
        bicycleSharing1.stop();
        bicycleSharing2.stop();
        bicycleSharing3.stop();

        BicycleSharing bicycleSharing = BicycleSharingFactory.getBicycleSharing(3);
        System.out.println(bicycleSharing==bicycleSharing3);
    }

}
//单车接口
interface Bicycle{
    void ride();
    void stop();
}
//共享单车
class BicycleSharing implements Bicycle{
    private int id;//单车编号
    int status = 0;//0 表示空闲，1表示占用
    BicycleSharing(int id){
        this.id = id;
    }
    BicycleSharing(){
    }
    @Override
    public void ride() {
        this.status = 1;
        System.out.println("共享单车"+id+"被占用");
    }
    @Override
    public void stop() {
        this.status = 0;
        System.out.println("共享单车"+id+"被释放");
    }
}
//共享单车工厂
class BicycleSharingFactory{
    private int id;
    //享元池,用的是单例模式
    private static Map<Integer,BicycleSharing> map = new HashMap<>();

    public static BicycleSharing getBicycleSharing(int id){
        if(map.containsKey(id)){
            return map.get(id);
        }
        BicycleSharing bicycleSharing = new BicycleSharing(id);
        map.put(id,bicycleSharing);
        return bicycleSharing;
    }
}
